package com.hulytu.dev2;


import com.hulytu.dev2.plugin.EnhancePlugin;

import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.util.Objects;

public class Platform {

    private static final EnhancePlugin EMPTY = new EmptyEnhancePlugin();

    private static final Object LOCK = new Object();

    private static Embrace embrace;

    public static void init() {
        init(null);
    }

    /**
     * 初始化
     */
    public static void init(Embrace emb) {
        synchronized (LOCK) {
            if (embrace != null) return;

            embrace = emb == null ? new Embrace() : emb;
            embrace.onAppInit();
        }
    }

    public static void destroy() {

        synchronized (LOCK) {
            final Embrace cache = embrace;
            if (cache != null) {
                cache.onDestroyed();
            }
        }
    }

    @NotNull
    public static Embrace get() {
        return Objects.requireNonNull(embrace, "Pls init before get.");
    }

    /**
     * 如果没有初始化，则进行一次初始化后返回
     *
     * @return
     */
    @NotNull
    public static Embrace opt() {
        if (embrace != null) return embrace;
        init();
        return embrace;
    }

    @Nullable
    public static EnhancePlugin obtain(String alias) {
        return embrace == null ? null : embrace.obtain(alias);
    }

    @NotNull
    public static EnhancePlugin obtainNullable(String alias) {
        EnhancePlugin plugin = obtain(alias);
        return plugin == null ? EMPTY : plugin;
    }

    static class EmptyEnhancePlugin implements EnhancePlugin {

        @Override
        public void init() {

        }

        @Override
        public void destroy() {

        }

        @Override
        public Object invoke(Object callback, String method, Object... args) {
            return null;
        }
    }
}
